<?php


namespace wx\pay;


use wx\lib\data\WxPayNotifyReply;
use wx\lib\data\WxPayNotifyResults;
use wx\lib\data\WxPayOrderQuery;
use wx\lib\WxPayApi;
use wx\lib\WxPayException;

class Notify
{
    public $config;

    public function __construct()
    {
        $this->config = new WxPayConfig();
    }

    /**
     * 获取微信支付回调数据
     * @return array
     * @throws WxPayException
     */
    public function get_data()
    {
        $objData = WxPayNotifyResults::Init($this->config, file_get_contents('php://input'));
        $data = $objData->GetValues();
        //TODO 1、进行参数校验
        if (!array_key_exists("return_code", $data)
            || (array_key_exists("return_code", $data) && $data['return_code'] != "SUCCESS")) {
            //TODO失败,不是支付成功的通知
            //如果有需要可以做失败时候的一些清理处理，并且做一些监控
            throw new WxPayException("return_code异常");
        }
        if (!array_key_exists("transaction_id", $data)) {
            throw new WxPayException("微信支付订单号不存在");
        }
        //查询订单，判断订单真实性
        if (!$this->query_order($data["transaction_id"])) {
            throw new WxPayException("订单查询失败");
        }
        return $data;
    }

    /**
     * 查询订单
     * @param $transaction_id
     * @return bool|array
     * @throws WxPayException
     */
    public function query_order($transaction_id)
    {
        $input = new WxPayOrderQuery();
        $input->SetTransaction_id($transaction_id);
        $result = WxPayApi::orderQuery($this->config, $input);
        if (array_key_exists("return_code", $result)
            && array_key_exists("result_code", $result)
            && $result["return_code"] == "SUCCESS"
            && $result["result_code"] == "SUCCESS") {
            return $result;
        }
        return false;
    }

    /**
     * 回调处理完 返回给微信
     * @throws WxPayException
     */
    public function return_ok()
    {
        $data = new WxPayNotifyReply();
        $data->SetReturn_code('SUCCESS');
        $data->SetReturn_msg('OK');
        return $data->ToXml();
    }
}